package controller;

import java.awt.Color;
import java.io.*;
import java.net.Socket;
import java.util.*;

import controller.ClientHandler;
import model.MetaDeckModel;
import model.Position;
import view.MetaDeckFrame;

public class MetaDeckController {
	
	private MetaDeckFrame view;
	private MetaDeckModel model;
	private GameController game;
	private ChatController chat;
	private String myName;
	private static MetaDeckController self;
	private Map<String, Color> playerColors;
	
	public static void main(String args[]) {
		self = new MetaDeckController();
		self.init();
	}
	public static MetaDeckController getInstance() {
		return self;
	}
	private MetaDeckController() {
		
	}
	private void init() {
		myName = "user"+(int)(Math.random()*100000);
		model = new MetaDeckModel();
		view = new MetaDeckFrame(model);
		game = new GameController(model.getGame(), view.getGame());
		chat = new ChatController(model.getChat(), view.getChat());
		playerColors = new HashMap<String, Color>();
		

		try {
			Socket socket = new Socket("127.0.0.1", 4444);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			ClientHandler hander = new ClientHandler(in,out,this);	
			Thread handlerThread = new Thread(hander);
			handlerThread.start();
			Thread.sleep(100);
			
			//TODO a hack for now
			ClientHandler.loginRequest(myName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		model.changePosition(myName, Position.SOUTH);
		model.changePosition("Computer", Position.NORTH);
		playerColors.put(myName, Color.RED);
		playerColors.put("Computer", Color.BLUE);
		
		//Do this after everything else has been initialized
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		view.setVisible(true);
		
	}
	public String getMyName() {
		return myName;
	}
	public Position getMyPosition() {
		return model.getPosition(myName);
	}
	public Color getPlayerColor(String name) {
		return playerColors.get(name);
	}
	public GameController getGame() {
		return game;
	}
	public ChatController getChat() {
		return chat;
	}
}
